﻿#ifndef __SINGLETONSAFE_H__
#define __SINGLETONSAFE_H__

#include <thread>
#include <mutex>

#include "noncopyable.h"


//哨兵类，负责多线程操作，自动加锁解锁
//哨兵类不允许拷贝，
template<typename T>
class SingletonGuard : std::unique_lock<std::mutex>, public noncopyable
{
public:
	explicit SingletonGuard(T* inst, std::mutex& mt):std::unique_lock<std::mutex>(mt),m_guardPtr(inst)
	{		 
	}
	SingletonGuard(SingletonGuard<T>&& guard) :m_guardPtr(guard.m_guardPtr)
	{
		guard.m_guardPtr = nullptr;
	}
	T* operator->()const
	{
		return m_guardPtr;
	}
private:
	T* m_guardPtr;
};

//线程安全单例
template<typename T>
class SingletonSafe : public noncopyable
{
public:

	static SingletonGuard<T> get_mutable_instance(){
		return SingletonGuard<T>(&get_instance(), m_signalMutex);
	}

	static const T & get_const_instance(){
		return get_instance();
	}
private:
	static T & instance;
	static void do_nothing(T const &) {}
	static T & get_instance() {
		static T ins;
		do_nothing(instance);
		return ins;
	}
	static std::mutex m_signalMutex; 
};
template<typename T>
std::mutex SingletonSafe< T >::m_signalMutex;

template<typename T>
T & SingletonSafe< T >::instance = SingletonSafe< T >::get_instance();

#endif //__SINGLETONSAFE_H__